//
//  Status.swift
//  XJWeiBo
//
//  Created by 徐健 on 16/3/15.
//  Copyright © 2016年 徐健. All rights reserved.
//

import UIKit
import AFNetworking

class Status: NSObject {
    //创建时间
    var created_at:String?
    
    var id:Int64 = 0
    
    var text : String?
    //来源
    var source :String?
    
    
    var User : user?
    
    
    
    init(dict:[String : AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    
    override func setValue(value: AnyObject?, forKey key: String) {
        if key == "user"{
            guard let dict = value as? [String : AnyObject] else{
                //不能转为字典
                return
            }
            
            User = user(dict: dict)
            
            return
        }
        
        super.setValue(value, forKey: key)
    }
    
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    
    
    //重写描述方法
    override var description:String{
        let key = ["id","text","created_at","source"]
        let dict = self.dictionaryWithValuesForKeys(key)
        
        return dict.description
    }

    
}


//网络访问

extension Status{
    class func loadHomeData(finished:(array:[Status]?)->()){
        guard let token = userAccount.onlyUserAccount.access_token else{
            print("用户未登录")
            return
        }
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        let parameters = ["access_token":token]
        
        let AFN = AFHTTPSessionManager()
        
        AFN.GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            
            //返回数据转为字典
            guard let dic = result as?[String:AnyObject] else{
                
                finished(array: nil)
                
                print("数据错误")
                return
            }
            
            //得到数组
            guard let array = dic["statuses"] as? [[String : AnyObject]] else{
                finished(array: nil)
                print("数据错误")
                return
            }
            
            var tempArray = [Status]()
            
            //遍历数组
            for item in array{
                //字典转模型
                
                let s = Status(dict: item)
                
                tempArray.append(s)

            }
            
            //传递数据刷新页面
            finished(array: tempArray)
            
            
            }) { (_, error) -> Void in
                
                finished(array: nil)
                
                print(error)
        }
        
    }
}